<?php

namespace IMT\Plugins\OrderBundle\Controller;

use IMT\Plugins\OrderBundle\Entity\Ordre;

use IMT\EventBundle\Entity\Event;

use IMT\OrderBundle\Entity\Attachment;

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;


class DefaultController extends Controller
{
    
    public function indexAction()
    {
        return $this->forward('IMTPluginsOrderBundle:Default:show', array(
        	'idEvent' => 0
    	));
    }
    
    public function showAction($idEvent, $type)
    {
    	$emEvent = $this->get('imt_event.'.$type.'_manager');
    	$securityContext = $this->get('security.context');
    	$user = $securityContext->getToken()->getUser();
    	 
    	$participants = array();
    	
    	if($idEvent != 0){
    		$event = $emEvent->findEventBy(array('id' => $idEvent));
    		 
    		if(!$event)
    			throw $this->createNotFoundException('L\'événement recherché n\'existe pas');
    	} else 
    		$event = $emEvent->createEvent();
    	    	 
    	return $this->render('IMTPluginsOrderBundle:Default:index.html.twig', array(
    		'event' => $event,
    	));
    }
    
    public function updateAJAXAction($idEvent, $type)
    {
    	$return = array('result' => 500, 'msg' => 'Une erreur inconnue est survenue');
    
    	try {
    		$request = $this->getRequest();
    		$em = $this->getDoctrine()->getEntityManager();
    		 
    		if('POST' == $request->getMethod()){
    
    			$emEvent = $this->container->get('imt_event.'.$type.'_manager');
    			$validator = $this->get('validator');
    			
    			$orderRepo = $em->getRepository('IMTPluginsOrderBundle:Ordre');
    			 
    			if($idEvent != 0){
    				$event = $emEvent->findEventBy(array('id' => $idEvent));
    			}
    			 
    			if(!$event)
    				throw $this->createNotFoundException('L\'événement à modifier n\'existe pas');
    			
    			$ordersTemp = $request->request->get('orders');
    			$orders = array();
    			$event->setOrders($orders);
    			
    			foreach ($ordersTemp as $id => $order){
    				$orderTemp = new Ordre();
    				
    				if(intval($order['isDelete']) == 1){
    					$orderTemp = $orderRepo->find($order['id']);
    					
    					if($orderTemp){
    						$em->remove($orderTemp);
    						$em->flush();
    					}
    				} else {
	    				if(intval($order['isNew']) == 0){
	    					$orderTemp = $orderRepo->find($order['id']);
	    				}
	    				
	    				$orderTemp->setContent($order['content']);
	    				$orderTemp->setEvent($event);
	    				$orderTemp->setState($order['state']);
	    				$orderTemp->setPosition($order['position']);
	    				
	    				$event->addOrder($orderTemp);
    				}
    			}
    			
    			$em->persist($event);
    			$em->flush();
    			
    			foreach($event->getOrders() as $order){
    				$orders[] = array('id' => $order->getId(), 'count' => $id);
    			}
    			
    			$return['result'] = 200;
    			$return['orders'] = $orders;
    			$return['msg'] = 'L\'ordre du jour a été modifié';
    			
    		} else {
    			throw new MethodNotAllowedException('POST');
    		}
    	} catch(NotFoundHttpException $e){
    		return new Response(json_encode(array('result' => 500, 'msg' => $e->getMessage())));
    	} catch(AccessDeniedException $e){
    		return new Response(json_encode(array('result' => 500, 'msg' => $e->getMessage())));
    	} catch(\Exception $e){
    		return new Response(json_encode(array(
    				'result' => 500,
    				'msg' => 'Une erreur est survenue au niveau du serveur',
    				'debug' => $e->getMessage()
    		)));
    	}
    	 
    	return new Response(json_encode($return));
    }
    
}
